﻿using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using Model;
using System.Web.Script.Serialization;
using System.Collections.Generic;

namespace SuuntoWebsite.Events._201205.Handler
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Event : IHttpHandler
    {
        private static string sqlCon = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString_Event"].ConnectionString;
        private static string webDomain = System.Configuration.ConfigurationManager.AppSettings["WebDomain"];
        protected string beginTimeStr = System.Configuration.ConfigurationManager.AppSettings["begintime"];
        protected string endTimeStr = System.Configuration.ConfigurationManager.AppSettings["endtime"];
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.UrlReferrer != null && context.Request.UrlReferrer.Authority.Equals(webDomain.Replace("http://", "")))
            {
                string flag = context.Request["flag"];
                switch (flag)
                {
                    case "reguser":
                        {
                            SuuntoUserInsert(context);
                            break;
                        }
                    case "answer":
                        {
                            SuuntoAnswerInsert(context);
                            break;
                        }
                    case "count":
                        {
                            SuuntoProductsCount(context);
                            break;
                        }
                    case "citylist":
                        {
                            SuuntoStroeCityList(context);
                            break;
                        }
                    case "addresslist":
                        {
                            SuuntoStoreAddressList(context);
                            break;
                        }
                    case "address":
                        {
                            SuuntoStoreAddressSave(context);
                            break;
                        }
                    case "check":
                        {
                            CheckTime(context);
                            break;
                        }
                    default:
                        break;
                }
            }
            else
            {
                ResultMessage(context, "Error");
            }
        }
        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="context"></param>
        private void SuuntoUserInsert(HttpContext context)
        {
            Model.ModelEvent.ModelSuunto_Users model=new ModelEvent.ModelSuunto_Users();
            model.PKID = new Bll.EventForSuunto.BLLSuunto_Users().GetUserID(sqlCon);
            model.Username = context.Request["name"];
            model.Gender = context.Request["sex"];
            model.Age = context.Request["age"];
            model.Profession = context.Request["profession"];
            model.Address = context.Request["address"];
            model.ZipCode = context.Request["zipcode"];
            model.Email = context.Request["email"];
            model.Phone = context.Request["phone"];
            string returnStr= new Bll.EventForSuunto.BLLSuunto_Users().SuuntoUsersInsert(sqlCon, model);
            if (!string.IsNullOrEmpty(returnStr))
            {
                ResultMessage(context, "true");
                Public.Cookie.UserId = returnStr;
                Public.Cookie.UserName = model.Username;
            }
            else
                ResultMessage(context, "false");

        }
        /// <summary>
        /// 问题回答
        /// </summary>
        /// <param name="context"></param>
        private void SuuntoAnswerInsert(HttpContext context)
        {
            string[] question ={
                                  "1. 您是否之前有购买过SUNNTO产品？",
                                  "2. 您从何种渠道知道SUNNTO品牌及产品信息的？",
                                  "3. 您从何种渠道知道此次活动的信息？",
                                  "4. 您喜欢AMBIT的功能是",
                                  "5. 您喜欢从事的运动是",
                                  "6. 您希望在商场中的哪个区域能有SUUNTO产品专柜？"                                  
                              };
            string[] answer = context.Request["answer"].Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
            int i=0;
            bool flag = false;
            foreach (string s in question)
            {
                Model.ModelEvent.ModelSuunto_Answer model = new ModelEvent.ModelSuunto_Answer();
                model.UID = Public.Cookie.UserId;
                model.Question = s;
                model.Answer = answer[i];
                model.CreateTime = DateTime.Now;
                flag = new Bll.EventForSuunto.BLLSuunto_Answer().AnswerInsert(sqlCon, model);
                if (flag == false)
                    break;
                i++;
            }
            ResultMessage(context, flag.ToString().ToLower());
        }
        /// <summary>
        /// 库存查询
        /// </summary>
        /// <param name="context"></param>
        private void SuuntoProductsCount(HttpContext context)
        {
            int pkid = Convert.ToInt32(context.Request["pkid"]);
            bool flag = new Bll.EventForSuunto.BLLSuunto_Products().SuuntoProductsCount(sqlCon, pkid);
            ResultMessage(context, flag.ToString().ToLower());
        }
        /// <summary>
        /// 商店城市列表
        /// </summary>
        /// <param name="context"></param>
        private void SuuntoStroeCityList(HttpContext context)
        {
            DataTable dt = new Bll.EventForSuunto.BLLSuunto_Store().SuuntoStoreList(sqlCon);
            ArrayList array = new ArrayList();
            foreach (DataRow dr in dt.Rows)
            {
                bool flag=true;
                foreach (string s in array)
                {
                    if (dr["S_City"].ToString() == s)
                    { flag = false; break; }
                }
                if (flag) array.Add(dr["S_City"]);
            }
            JavaScriptSerializer JSONSerializer = new JavaScriptSerializer();
            string json=JSONSerializer.Serialize(array);
            ResultJson(context, json);

        }
        /// <summary>
        /// 商店地址列表
        /// </summary>
        /// <param name="context"></param>
        private void SuuntoStoreAddressList(HttpContext context)
        {
            DataTable dt = new Bll.EventForSuunto.BLLSuunto_Store().SuuntoStoreList(sqlCon);
            string city = context.Request["city"];
            JavaScriptSerializer JSONSerializer = new JavaScriptSerializer();
            DataRow[] dr = dt.Select("S_City='" + city + "'");
            //ArrayList array = new ArrayList();
            Dictionary<string, string> array = new Dictionary<string, string>();
            foreach (DataRow drr in dr)
            {
                array.Add(drr["PKID"].ToString(), drr["S_Name"].ToString()+"—"+drr["S_Address"].ToString());
            }
            string json = JSONSerializer.Serialize(array);
            ResultJson(context, json);
        }
        /// <summary>
        /// 保存商店地址到Cookie
        /// </summary>
        /// <param name="context"></param>
        private void SuuntoStoreAddressSave(HttpContext context)
        {
            Public.Cookie.StoreId = context.Request["store"];
            if (Public.Cookie.StoreId != "0")
                ResultMessage(context, "true");
        }
        protected void CheckTime(HttpContext context)
        {
            bool flag = false;
            DateTime nowTime = DateTime.Now;
            DateTime beginTime = Convert.ToDateTime(beginTimeStr);
            DateTime endTime = Convert.ToDateTime(endTimeStr);
            if (nowTime.CompareTo(beginTime) > 0 && nowTime.CompareTo(endTime) < 0)
            {
                ResultMessage(context, "true");
            }
            else if(nowTime.CompareTo(beginTime)<0)
            {
                ResultMessage(context,"活动尚未开始！");
            }
            else if(nowTime.CompareTo(endTime)>0)
            {
                ResultMessage(context, "活动已结束！");
            }
        }
        /// <summary>
        /// 返回结果：message
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        private void ResultMessage(HttpContext context,string message)
        {
            context.Response.ContentType = "text/plain";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            context.Response.Write(message);
        }
        /// <summary>
        /// 返回结果：json
        /// </summary>
        /// <param name="context"></param>
        /// <param name="json"></param>
        private void ResultJson(HttpContext context,string json)
        {
            context.Response.ContentType = "json/application";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            context.Response.Write(json);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
